package gcvalid

import (
	"errors"
	"regexp"

	"gitee.com/githubdog/goci/tools/helper"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

// ValidPackageName 验证包名格式
func ValidPackageName(fl validator.FieldLevel) bool {
	re := regexp.MustCompile(`^([a-zA-Z_][a-zA-Z0-9_]*)+([\.][a-zA-Z_][a-zA-Z0-9_]*)+$`)
	val := fl.Field().Interface()
	if v, ok := val.(string); ok {
		if find := re.FindString(v); find != "" {
			return true
		}
	}
	return false
}

// ValidCNMobile 验证中国手机号码格式
func ValidCNMobile(fl validator.FieldLevel) bool {
	val := fl.Field().Interface()
	if v, ok := val.(string); ok {
		if v == "" {
			return true
		}
		return helper.CheckZhMobileFormat(v)
	}
	return false
}

// ValidEmail 验证邮箱(可为空, gin自带的不可为空)
func ValidEmail(fl validator.FieldLevel) bool {
	re := regexp.MustCompile("^(?:(?:(?:(?:[a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+(?:\\.([a-zA-Z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])+)*)|(?:(?:\\x22)(?:(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(?:\\x20|\\x09)+)?(?:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}]))))*(?:(?:(?:\\x20|\\x09)*(?:\\x0d\\x0a))?(\\x20|\\x09)+)?(?:\\x22))))@(?:(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|\\d|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.)+(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])|(?:(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])(?:[a-zA-Z]|\\d|-|\\.|~|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])*(?:[a-zA-Z]|[\\x{00A0}-\\x{D7FF}\\x{F900}-\\x{FDCF}\\x{FDF0}-\\x{FFEF}])))\\.?$")
	val := fl.Field().Interface()
	if v, ok := val.(string); ok {
		if v == "" {
			return true
		}
		if find := re.FindString(v); find != "" {
			return true
		}
	}
	return false
}

func BindCoutomValida(m map[string]func(validator.FieldLevel) bool) (err error) {
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		for key, val := range m {
			if err = v.RegisterValidation(key, val); err != nil {
				break
			}
		}
	} else {
		err = errors.New("binding.Validator.Engine error")
	}
	return
}
